//
//  GroupPerformanceViewController.m
//  QinrenManagers
//
//  Created by easaa on 15/5/29.
//  Copyright (c) 2015年 easaa. All rights reserved.
//

#import "GroupPerformanceViewController.h"
#import "GroupPerModel.h"
#import "BottomModel.h"

#import "GroupPerformanceCell.h"

//下拉框
#import "ComboBoxView.h"


@interface GroupPerformanceViewController ()<UITableViewDataSource,UITableViewDelegate,sendSelectecdIndexDelegate>
{
    ComboBoxView  *_comboBox;
    NSInteger _comboxSelectedIndex;
    
    /**排序按钮*/
    UIButton * _sortButton;
    
    BOOL _needRefresh;
    
    
    UIView * _bottomView;
}
@property (nonatomic, strong) UITableView * groupScoreTableView;

@property (nonatomic, strong) NSMutableArray * dataSource;

@property (nonatomic, strong) NSMutableArray * bottomDataSource;

@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, assign) NSInteger sortIndex;

@end

@implementation GroupPerformanceViewController

#pragma mark - ================= 各初始化方法 =================

- (instancetype)init
{
    self = [super init];
    if (self) {
        _dataSource = [NSMutableArray array];
        _bottomDataSource = [NSMutableArray array];
        _pageIndex = 1;
        _sortIndex = 0;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = Lightlightcolor;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self requestForData];
    
    [self creatUI];

}

- (void)requestForData
{
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    User *user = [User sharedUser];
    
    NSDictionary *parameters = @{@"id":user.employee_id,@"pagesize":@"10",@"pageindex":[NSString stringWithFormat:@"%ld",(long)_pageIndex],@"time":[NSString stringWithFormat:@"%ld",(long)_comboxSelectedIndex],@"ordertype":[NSString stringWithFormat:@"%ld",(long)_sortIndex]};
    
    NSLog(@"%@",parameters);
    
    [manager GetWithParameters:parameters method:@"get.manager.teamscore" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
            NSString *resposeString ;
        
            if ([responseObject isKindOfClass:[NSData class]]) {
                resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            }else{
                resposeString = responseObject;
            }
        
        
        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"团队业绩的dictonary :%@",[dictionary description]);
        
        
        if ([[dictionary objectForKey:@"verification"]intValue] == 1)
        {

            if (_needRefresh) {
                [SVProgressHUD showSuccessWithStatus:@"请求数据中"];
                [_dataSource removeAllObjects];
            }
            if ([dictionary[@"total"] integerValue] >0) {
                for (NSDictionary *dataDic in dictionary[@"data"]) {
                    
                    GroupPerModel *groupPerModel = [[GroupPerModel alloc]init];
                    
                    [groupPerModel setValuesForKeysWithDictionary:dataDic];
                    
                    [_dataSource addObject:groupPerModel];
                    
                    [_groupScoreTableView reloadData];
                    
                }

            }
            
            
            if ([dictionary[@"total"] integerValue] < 10) {
                
                //[_personalTableView.footer resetNoMoreData];
                
                [_groupScoreTableView.footer endRefreshing];
                [_groupScoreTableView.header endRefreshing];
                [_groupScoreTableView.footer noticeNoMoreData];
                return ;
            }

            
        }else
        {
            NSString *error = [dictionary objectForKey:@"error"];
//            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
            //[SVProgressHUD showErrorWithStatus:error];
        }
        
        [_groupScoreTableView.footer endRefreshing];
        [_groupScoreTableView.header endRefreshing];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
    }];
    
}

- (void)requestForBottomData
{
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    User *user = [User sharedUser];
    
    NSDictionary *parameters = @{@"id":user.employee_id};
    NSLog(@"%@",parameters);
    [manager GetWithParameters:parameters method:@"search.manager.teamscore" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;

        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"团队底部的dictonary :%@",[dictionary description]);


        if ([[dictionary objectForKey:@"verification"]intValue] == 1 && [[dictionary objectForKey:@"total"]intValue]>0)
        {
            for (NSDictionary *dataDic in dictionary[@"data"]) {

                BottomModel *bottomModel = [[BottomModel alloc]init];
                [bottomModel setValuesForKeysWithDictionary:dataDic];
                [_bottomDataSource addObject:bottomModel];

            }
            
            
            [self creatBottom];

        }
        else
        {

//            NSString *error = [dictionary objectForKey:@"error"];
//            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
//            [SVProgressHUD showErrorWithStatus:error];
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];

    }];

}


- (void)headerRefresh{
    _needRefresh = YES;
    _pageIndex = 1;
    [self requestForData];
}
- (void)footerRefresh{
    _needRefresh = NO;
    _pageIndex ++;
    [self requestForData];
}

- (void)creatUI
{
    _sortButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W/2-1, 35)];
    
    _sortButton.backgroundColor = [UIColor whiteColor];
    
    [_sortButton setImage:[UIImage imageNamed:@"paixu_"] forState:UIControlStateNormal];//给button添加image
    _sortButton.imageEdgeInsets = UIEdgeInsetsMake(0,0,0,-CGRectGetMaxX(_sortButton.frame));//设置image在button上的位置（上top，左left，下bottom，右right）这里可以写负值，对上写－5，那么image就象上移动5个像素
    
    
    [_sortButton setTitle:@"排序" forState:UIControlStateNormal];//设置button的title
    //_sortButton.titleLabel.font = [UIFont systemFontOfSize:16];//title字体大小
    _sortButton.titleLabel.font = [UIFont fontWithName:@"Arial" size:12.0f];
    _sortButton.layer.cornerRadius = 5;
    _sortButton.clipsToBounds = YES;
    _sortButton.titleLabel.textAlignment = NSTextAlignmentCenter;//设置title的字体居中
    [_sortButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//设置title在一般情况下为白色字体
    [_sortButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];//设置title在button被选中情况下为灰色字体
    //_sortButton.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);//设置title在button上的位置（上top，左left，下bottom，右right）
    
    
    [_sortButton addTarget:self action:@selector(reloadDataForTableView) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:_sortButton];
    [self creatTableView];

    [self creatComBox];

    [self requestForBottomData];


}
  //创建下拉框
- (void)creatComBox
{
    
    
    NSArray *comboBoxDatasource = [[NSArray alloc] initWithObjects:@"全部", @"本周", @"本月", @"最近三月", @"最近半年", @"最近一年", nil];
    
    _comboBox = [[ComboBoxView alloc] initWithFrame:CGRectMake(SCREEN_W/2+1 , 0, SCREEN_W/2-10, 180)];
    
    _comboBox.comboBoxDatasource = comboBoxDatasource;
    _comboBox.backgroundColor = [UIColor clearColor];
    _comboBox.delegate = self;
    [_comboBox setContent:[comboBoxDatasource objectAtIndex:0]];
    
    
    [self.view addSubview:_comboBox];

}


- (void)creatBottom
{
    //[self requestForBottomData];
    
    _bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_H-185, SCREEN_W, 120)];
    _bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_bottomView];
    
    if (_bottomDataSource.count == 1) {
        
        BottomModel *bottomModel = _bottomDataSource[0];
        
        UILabel * headerLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, _bottomView.frame.size.width-10, 30 )];
        
        NSString *headerLabalText = [NSString stringWithFormat:@"本月团队提成%@分",bottomModel.commission_score];
        headerLabel.text = headerLabalText;
        headerLabel.textColor = [UIColor redColor];
        headerLabel.font = [UIFont fontWithName:@"Arial" size:19.0f];
        [_bottomView addSubview:headerLabel];
        
        //细线
        UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 40, _bottomView.frame.size.width, 1)];
        lineView.backgroundColor = [UIColor grayColor];
        [_bottomView addSubview:lineView];
        
        UILabel * bottomScoreLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, CGRectGetMaxY(lineView.frame) + 2, _bottomView.frame.size.width-10, 25 )];
        
        NSString * num1 = bottomModel.regular_score;
        
        //@"本月业绩考核指标3000分"
        NSMutableAttributedString *str1 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"本月业绩考核指标%@分",num1]];
        
        [str1 addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,8)];
        [str1 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(8,str1.length - 9)];
        [str1 addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(str1.length - 1,1)];
        
        bottomScoreLabel.attributedText = str1;
        bottomScoreLabel.font = [UIFont fontWithName:@"Arial" size:12.0f];
        [_bottomView addSubview:bottomScoreLabel];
        
        UILabel * bottomGroupNumLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, CGRectGetMaxY(bottomScoreLabel.frame), _bottomView.frame.size.width-10, 25 )];
        
        NSString * num2 = bottomModel.regular_count;
        
        //本月合格下属机构5个
        NSMutableAttributedString *str2 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"本月合格下属机构%@个",num2]];
        
        [str2 addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,8)];
        [str2 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(8,str2.length - 9)];
        [str2 addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(str2.length - 1,1)];
        
        bottomGroupNumLabel.attributedText = str2;
        
        bottomGroupNumLabel.font = [UIFont fontWithName:@"Arial" size:12.0f];
        [_bottomView addSubview:bottomGroupNumLabel];
        
        UILabel * bottomGroupScoreLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, CGRectGetMaxY(bottomGroupNumLabel.frame), _bottomView.frame.size.width-10, 25 )];
        
        
        NSString * num3 = bottomModel.regular_total;
        
        //本月合格团队业绩10000分
        NSMutableAttributedString *str3 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"本月合格团队业绩%@分",num3]];
        
        [str3 addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,8)];
        [str3 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(8,str3.length-9)];
        [str3 addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(str3.length-1,1)];
        
        bottomGroupScoreLabel.attributedText = str3;
        
        bottomGroupScoreLabel.font = [UIFont fontWithName:@"Arial" size:12.0f];
        [_bottomView addSubview:bottomGroupScoreLabel];

        
    }
    else{
    
        UILabel * headerLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, _bottomView.frame.size.width-10, 30 )];
        
        headerLabel.text = @"本月团队提成0分";
        headerLabel.textColor = [UIColor redColor];
        headerLabel.font = [UIFont fontWithName:@"Arial" size:19.0f];
        [_bottomView addSubview:headerLabel];
        
        //细线
        UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 40, _bottomView.frame.size.width, 1)];
        lineView.backgroundColor = [UIColor grayColor];
        [_bottomView addSubview:lineView];
        
        UILabel * bottomScoreLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, CGRectGetMaxY(lineView.frame) + 2, _bottomView.frame.size.width-10, 25 )];
        
        NSString * num1 = @"0";
        
        //@"本月业绩考核指标3000分"
        NSMutableAttributedString *str1 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"本月业绩考核指标%@分",num1]];
        
        [str1 addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,8)];
        [str1 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(8,str1.length - 9)];
        [str1 addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(str1.length - 1,1)];
        
        bottomScoreLabel.attributedText = str1;
        bottomScoreLabel.font = [UIFont fontWithName:@"Arial" size:12.0f];
        [_bottomView addSubview:bottomScoreLabel];
        
        UILabel * bottomGroupNumLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, CGRectGetMaxY(bottomScoreLabel.frame), _bottomView.frame.size.width-10, 25 )];
        
        NSString * num2 = @"0";
        
        //本月合格下属机构5个
        NSMutableAttributedString *str2 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"本月合格下属机构%@个",num2]];
        
        [str2 addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,8)];
        [str2 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(8,str2.length - 9)];
        [str2 addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(str2.length - 1,1)];
        
        bottomGroupNumLabel.attributedText = str2;
        
        bottomGroupNumLabel.font = [UIFont fontWithName:@"Arial" size:12.0f];
        [_bottomView addSubview:bottomGroupNumLabel];
        
        UILabel * bottomGroupScoreLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, CGRectGetMaxY(bottomGroupNumLabel.frame), _bottomView.frame.size.width-10, 25 )];
        
        
        NSString * num3 = @"0";
        
        //本月合格团队业绩10000分
        NSMutableAttributedString *str3 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"本月合格团队业绩%@分",num3]];
        
        [str3 addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,8)];
        [str3 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(8,str3.length-9)];
        [str3 addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(str3.length-1,1)];
        
        bottomGroupScoreLabel.attributedText = str3;
        
        bottomGroupScoreLabel.font = [UIFont fontWithName:@"Arial" size:12.0f];
        [_bottomView addSubview:bottomGroupScoreLabel];
    
    }
    
}

- (void)creatTableView
{
    _groupScoreTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_sortButton.frame)+1, SCREEN_W, SCREEN_H-64-27-130) style:UITableViewStylePlain];
    _groupScoreTableView.backgroundColor = [UIColor clearColor];
    _groupScoreTableView.delegate = self;
    _groupScoreTableView.dataSource = self;
    
    UINib * nib = [UINib nibWithNibName:@"GroupPerformanceCell" bundle:nil];
    
    [_groupScoreTableView registerNib:nib forCellReuseIdentifier:@"groupCell"];
    _groupScoreTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    
    
    
    __weak typeof(self) weakSelf = self;
    [_groupScoreTableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf headerRefresh];
    }];
    [_groupScoreTableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf footerRefresh];
    }];

    
    [self.view addSubview:_groupScoreTableView];

}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataSource count];
    //return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"groupCell";
    GroupPerformanceCell *cell = (GroupPerformanceCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    if (cell == nil) {
        cell = (GroupPerformanceCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    }
    
    
    if(_dataSource)
    {
        cell.sequenceNumberLabel.text = [NSString stringWithFormat:@"%ld、",(long)indexPath.row+1];
        [cell fillCellWithModel:_dataSource[indexPath.row]];
    }
    return cell;
    
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

#pragma mark-sendSelectecdIndexDelegate
- (void)sendSelectedIndex:(NSInteger)selectedIndex{
    [_dataSource removeAllObjects];
    _pageIndex = 1;
    _comboxSelectedIndex = selectedIndex;
    [self requestForData];
}

#pragma mark-排序更新数据
- (void)reloadDataForTableView
{
    [_dataSource removeAllObjects];
    if(_sortIndex == 0)
    {
        _sortIndex = 1;
        _pageIndex = 1;
    }
    else if(_sortIndex == 1)
    {
        _sortIndex = 0;
        _pageIndex = 1;
    }
    
    [self requestForData];

}

@end
